package com.qire.manhua.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;

import com.qire.antscore.annotation.RouteMapping;
import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.card.FloorCard;
import com.qire.antsrouter.inject.Autowired;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.constant.CustomEvent;
import com.qire.common.inject.EventControllerInjector;
import com.qire.common.inject.ViewModelInjector;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.DialogFastBuildUtil;
import com.qire.common.support.base.BaseActivity;
import com.qire.common.constant.Navigation;
import com.qire.common.support.base.ProxyViewModel;
import com.qire.common.utils.FileManager;
import com.qire.common.utils.NoticeEventBus;
import com.qire.common.utils.NoticeEventBus.NoticeEvent;
import com.qire.common.utils.OSCompatUtil;
import com.qire.common.utils.PermissionsChecker;
import com.qire.common.utils.PermissionsChecker.ObtainWay;
import com.qire.common.utils.ThemeUtil;
import com.qire.common.utils.ToastHelper;
import com.qire.manhua.R;
import com.qire.manhua.controller.UserProfileEditController;
import com.qire.manhua.databinding.ActivityUserProfileEditBinding;
import com.qire.manhua.model.viewModel.IUserProfileEditViewModel;

import java.io.File;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

/**
 * 用户资料编辑
 */
@RouteMapping(path = Navigation.Page.UserProfileEditPage)
public class UserProfileEditActivity extends BaseActivity<ActivityUserProfileEditBinding> {

    private static final int CAMERA_CODE = 1;
    private static final int GALLERY_CODE = 2;

    @Autowired(injector = ViewModelInjector.class)
    ProxyViewModel<IUserProfileEditViewModel> viewModel;

    @Autowired(injector = EventControllerInjector.class)
    UserProfileEditController controller;

    @Override
    public int layoutRid() {
        return R.layout.activity_user_profile_edit;
    }

    @Override
    public void onBackPressed() {
        if(UserEntity.self.isIllegalName()) {
            DialogFastBuildUtil.builder(R.layout.dialog_common_prompt_light_r)
                    .setTextView(R.id.dialog_title, "请填写一个有效昵称！")
                    .setTextView(R.id.dialog_content, "昵称只能由数字、字母、中文组成，不能包含非法字符。")
                    .setTextView(R.id.dialog_button_dark, "下次再说", view -> super.onBackPressed())
                    .setTextView(R.id.dialog_button_light, "去填写昵称", controller::editNicknameBtnOnClick)
                    .show();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ThemeUtil.changeStatusBarLightOrDark(this, true, true);

        controller.onAddition(viewModel);
        initData();
    }

    private void initData() {
        viewModel.set("userIdText", UserEntity.self.idToText());
        viewModel.set("userPortrait", UserEntity.self.getPortrait());

        int dyeColor = Color.rgb(0x90, 0x90, 0x90);
        viewModel.set("nicknameText", StringUtil.dye(UserEntity.self.nicknameToText().toString(), "未设置", dyeColor));
        viewModel.set("genderText", StringUtil.dye(UserEntity.self.sexToText().toString(), "未设置", dyeColor));
        viewModel.set("birthdayText", StringUtil.dye(UserEntity.self.birthdayToText().toString(), "未设置", dyeColor));
        viewModel.set("cityText", StringUtil.dye(UserEntity.self.cityToText().toString(), "未设置", dyeColor));
    }


    /**
     * 拍照选择图片
     */
    public void chooseFromCamera() {
        final String[] PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        new PermissionsChecker(this, this::applyCamera)
                .setPermissionTips("奇热漫画需要获取(照相机)和(存储)权限，以保证漫画正常拍照并保存头像以及您的账号安全")
                .setPermissionDenyTip("奇热漫画需要获取(照相机)和(存储)权限，以保证漫画正常拍照并保存头像以及您的账号安全\n请在【设置-应用-奇热漫画-权限】中打开相关权限，以正常使用奇热漫画功能")
                .applyPermissions(PERMISSIONS);
    }


    /**
     * 从相册选择图片
     */
    public void chooseFromGallery() {
        final String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        new PermissionsChecker(this, this::applyGallery)
                .setPermissionTips("奇热漫画需要获取(存储)权限，以保证漫画正常使用相册选取头像以及您的账号安全")
                .setPermissionDenyTip("奇热漫画需要获取(存储)权限，以保证漫画正常使用相册选取头像以及您的账号安全\n请在【设置-应用-奇热漫画-权限】中打开相关权限，以正常使用奇热漫画功能")
                .applyPermissions(PERMISSIONS);
    }

    private void applyCamera(ObtainWay obtainWay) {
        if(obtainWay != ObtainWay.requestObtain) {
            ToastHelper.showToast("未获得授权，无法使用相机");
            return;
        }

        File captureFile = FileManager.buildTempHeadPortraitFile();
        if(FileManager.exists(captureFile)) {
            Uri captureUri = OSCompatUtil.uriFromFile(this, captureFile);

            // 缓存 file 及 uri 数据，以便从相机返回页面时使用，由于ViewModel并不会在页面推到后台时被回收，固用来保存。
            viewModel.set("captureFile", captureFile);
            viewModel.set("captureUri", captureUri);

            // 调用系统相机
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri);
            ActivityCompat.startActivityForResult(this, intent, CAMERA_CODE, null);
        }
    }

    private void applyGallery(ObtainWay obtainWay) {
        if(obtainWay != ObtainWay.requestObtain) {
            ToastHelper.showToast("未获得授权，无法使用相册");
            return;
        }

        //构建一个内容选择的Intent
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //设置选择类型为图片类型
        intent.setType("image/*");
        //打开图片选择
        ActivityCompat.startActivityForResult(this, intent, GALLERY_CODE, null);
    }

    /**
     * 通过Uri传递图像信息以供裁剪
     * @param uri 图片的URI
     */
    private void startImageZoom(Uri uri){
        Bitmap bitmap = OSCompatUtil.bitmapFromUri(this, uri);
        if(ObjectUtil.nonNull(bitmap)) {

            NoticeEventBus.NOTICE.subscribeEvent(CustomEvent.IMAGE_CUT_AND_SCALE, this::onCutAndScaleEvent);
            AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.ImageCutAndScalePage)
                    .withData("bitmap", bitmap)
                    .withData("cropWidth", 250)
                    .withData("cropHeight", 250)
                    .navigation();
        }
    }

    public boolean onCutAndScaleEvent(NoticeEvent<Bitmap> event) {
        Bitmap bitmap = event.getEventData();
        controller.editUserPortrait(bitmap);
        bitmap.recycle();
        NoticeEventBus.NOTICE.unSubscribeEvent(CustomEvent.IMAGE_CUT_AND_SCALE);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_CODE:
                //用户点击了取消
                if (resultCode == Activity.RESULT_CANCELED)
                    return;

                if (resultCode == Activity.RESULT_OK) {
                    if (FileManager.checkFileCanRead(viewModel.getToValue("captureFile"))) {
                        Uri captureUri = viewModel.getToValue("captureUri");
                        startImageZoom(captureUri);
                    }
                }
                break;
            case GALLERY_CODE:
                if (ObjectUtil.nonNull(data)) {
                    //获取到用户所选图片的Uri
                    Uri uri = data.getData();
                    startImageZoom(uri);
                }
                break;
            default:
                break;
        }
    }

}
